import md5 from 'js-md5'
import { login, getInfo, commons } from '@/api'
import { getToken, setToken, removeToken, setOssPolicy, getOssPolicy } from '@/utils/auth'
import moment from 'moment'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  userInfo: {},
  roles: [],
  // ossPolicy信息
  ossPolicy: {}
}

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
  },
  SET_USER_INFO: (state, data) => {
    state.userInfo = data
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  // ossPolicy信息写入
  SET_OSS_POLICY: (state, data) => {
    state.ossPolicy = data
  }
}

const actions = {
  login({ commit }, userInfo) {
    const { username, password, ip, lat, lng } = userInfo
    return new Promise((resolve, reject) => {
      let errorInfo
      login({ ip, lat, lng, userName: username.trim(), password: md5(password) })
        .then(response => {
          // 错误信息
          errorInfo = response

          const {
            data: { token }
          } = response

          commit('SET_TOKEN', token)
          setToken(token)
          resolve()
        })
        .catch(error => {
          console.log(error, 'error')
          reject(errorInfo)
        })
    })
  },
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then(response => {
          const { data, msg } = response
          if (!data) {
            reject(msg)
          }

          const {
            permission: { navList },
            avatar,
            userName,
            realName,
            telephone
          } = data

          if (!navList || navList.length <= 0) {
            reject('请分配权限给该账号')
          }

          commit('SET_ROLES', navList)
          commit('SET_USER_INFO', { avatar, userName, realName, telephone })
          resolve(navList)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },
  logout({ commit }) {
    commit('SET_TOKEN', '')
    commit('SET_ROLES', [])
    removeToken()
    resetRouter()
  },
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

    router.addRoutes(accessRoutes)
  },

  // 获得上传policy和签名
  async getPolicy({ commit }) {
    try {
      const res = await commons.getPolicy()
      const { data } = res
      // 参数处理--添加过期时间时间戳
      data.loseTime = moment()
        .add(data.expire - 5, 'seconds')
        .valueOf()
      commit('SET_OSS_POLICY', data)
      setOssPolicy(data)
    } catch (error) {
      console.log('getPolicy', error)
    }
  },
  // 刷新后重新从本地存储获取plicy
  resetPolicy({ commit }) {
    const policy = getOssPolicy()
    if (policy) commit('SET_OSS_POLICY', policy)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
